const configCenter = require("uni-config-center");
const crypto = require("crypto");
const config = configCenter({
	pluginId: 'vk-unicloud'
}).requireFile('index.js');

function objKeySort(arys, partner_key) {
	//先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序 
	var newkey = Object.keys(arys).sort();
	console.log('newkey=' + newkey);
	var newObj = '';
	//建立一个新的对象，用于存放排好序的键值对 
	for (var i = 0; i < newkey.length; i++) { //遍历newkey数组 
		newObj += [newkey[i]] + '=' + arys[newkey[i]] + '&';
	}
	return newObj.substring(0, newObj.length - 1) + '&partner_key=' + partner_key;
}
module.exports = {
	/**
	 * 修改数据
	 * @url admin/kong/sys/update 前端调用的url参数地址
	 * data 请求参数 说明
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: 'ok' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			_id,
			course_id,
			chapter_id,
			title,
			view_num,
			short_description,
			render_desc,
			published_at,
			is_show,
			comment_status,
			duration,
			free_seconds,
			ban_drag,
			tencent_video_id,
			aliyun_video_id,
			qiniu_video_id,
			room_id,
			url,
			use_type
		} = data;
		// 这里需要把 params1 params2 params3 改成你数据库里允许用户添加的字段
		if (vk.pubfn.isNullOne(_id)) {
			return { code: -1, msg: '参数错误' };
		}
		const {
			baijiayun
		} = config.vk;
		let start_time = new Date(published_at[0]).getTime()
		let end_time = new Date(published_at[1]).getTime()
		let private_domain = baijiayun.private_domain
		var baijiayunParmas = {
			partner_id: baijiayun.Partner_ID,
			room_id,
			title,
			start_time: start_time / 1000,
			end_time: end_time / 1000,
			timestamp: Date.now() / 1000
		}
		let str = objKeySort(baijiayunParmas, baijiayun.Partner_Key)
		console.log(str)
		let sign = crypto
			.createHash('md5')
			.update(str, 'utf-8')
			.digest('hex').toLowerCase()
		baijiayunParmas.sign = sign
		
		console.log(baijiayunParmas)
		let requestRes = await vk.request({
			url: `https://${private_domain}.at.baijiayun.com/openapi/room/update`,
			method: "POST",
			data: baijiayunParmas,
			useContent: false, // 是否需要将data请求参数转成body请求体
		});
		console.log(requestRes)
		if (requestRes.code != 0) {
			return {
				code: requestRes.code,
				msg: requestRes.msg
			}
		}
		
		let dbName = "live_course_videos";
		await vk.baseDao.updateById({
			dbName,
			id: _id,
			dataJson: {
				course_id,
				chapter_id,
				title,
				view_num,
				short_description,
				render_desc,
				published_at,
				is_show,
				comment_status,
				duration,
				free_seconds,
				ban_drag,
				tencent_video_id,
				aliyun_video_id,
				qiniu_video_id,
				url,
				use_type,
				start_time,
				end_time,
			}
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}

}
